// pages/consult/select/select.js
Page({
  data: {
    region: [],
    talents: [],
    grades: [],
    priceClassifies: [],
    genders: ["男", "女", "不限"],
    selectedGrade: { id: null, name: null },
    selectedGender: "不限",
    showGrade: false
  },

  onLoad() {
    this.getFilterOptions();
  },

  getFilterOptions() {
    wx.request({
      url: 'http://localhost:8080/counselor/sift',
      method: 'GET',
      success: (res) => {
        if (res.data.code === 200) {
          const data = res.data.data;
          this.setData({
            talents: data.talents.map(item => ({
              id: item.id,
              name: item.talentName,
              selected: false
            })),
            grades: data.grades.map(item => ({
              id: item.id,
              name: item.gradeName
            })),
            priceClassifies: data.priceClassifies.map(item => ({
              id: item.id,
              name: item.priceClassifyName,
              selected: false
            }))
          });
        } else {
          wx.showToast({ title: '获取筛选数据失败', icon: 'none' });
        }
      },
      fail: (err) => {
        console.error('获取筛选选项失败', err);
        wx.showToast({ title: '获取数据失败', icon: 'none' });
      }
    });
  },

  onRegionChange(e) {
    const [province, city] = e.detail.value;
    this.setData({ region: city ? [province, city] : [province] });
  },

  showGradePopup() { this.setData({ showGrade: true }); },
  closeGradePopup() { this.setData({ showGrade: false }); },

  chooseGrade(e) {
    const { id, name } = e.currentTarget.dataset;
    this.setData({ selectedGrade: { id, name }, showGrade: false });
  },

  chooseTalent(e) {
    const index = e.currentTarget.dataset.index;
    const talents = [...this.data.talents];
    const current = talents[index];
    
    if (current.selected) {
      current.selected = false;
    } else {
      const selectedCount = talents.filter(item => item.selected).length;
      if (selectedCount < 3) {
        current.selected = true;
      } else {
        wx.showToast({ title: '最多选择3个标签', icon: 'none' });
      }
    }
    this.setData({ talents });
  },

  choosePriceClassify(e) {
    const index = e.currentTarget.dataset.index;
    const priceClassifies = [...this.data.priceClassifies];
    priceClassifies[index].selected = !priceClassifies[index].selected;
    this.setData({ priceClassifies });
  },

  chooseGender(e) {
    this.setData({ selectedGender: e.currentTarget.dataset.gender });
  },

  resetFilter() {
    this.setData({
      region: [],
      selectedGrade: { id: null, name: null },
      selectedGender: "不限",
      talents: this.data.talents.map(item => ({ ...item, selected: false })),
      priceClassifies: this.data.priceClassifies.map(item => ({ ...item, selected: false })),
      showGrade: false
    });
  },

  submitFilter() {
    // 1. 处理参数（完全按照示例JSON的格式构造）
    let address = null;
    if (this.data.region.length >= 2 && this.data.region[1] && this.data.region[1] !== "请选择") {
      address = this.data.region[1];
    }

    let sex = null;
    if (this.data.selectedGender === "男") sex = 2;
    else if (this.data.selectedGender === "女") sex = 1;

    // 等级：构造与示例一致的 counselorGrade 对象
    const counselorGrade = this.data.selectedGrade.name 
      ? { gradeName: this.data.selectedGrade.name } 
      : null;

    // 价格：构造与示例一致的 priceStandards 数组
    const selectedPrices = this.data.priceClassifies.filter(item => item.selected);
    const priceStandards = selectedPrices.length > 0 
      ? selectedPrices.map(item => ({ counselorPriceClassify: { priceClassifyName: item.name } })) 
      : null;

    // 标签：构造与示例一致的 counselorTalents 数组
    const selectedTalents = this.data.talents.filter(item => item.selected);
    const counselorTalents = selectedTalents.length > 0 
      ? selectedTalents.map(item => ({ talent: { talentName: item.name } })) 
      : null;

    // 构造与示例完全一致的参数结构
    const filterParams = {};
    if (address) filterParams.address = address;
    if (sex !== null) filterParams.sex = sex;
    if (counselorGrade) filterParams.counselorGrade = counselorGrade;
    if (priceStandards) filterParams.priceStandards = priceStandards;
    if (counselorTalents) filterParams.counselorTalents = counselorTalents;

    console.log('最终筛选参数：', filterParams);

    // 2. 调用接口
    wx.request({
      url: 'http://localhost:8080/counselor/filter',
      method: 'POST',
      header: {
        'Content-Type': 'application/json' // 确保以 JSON 格式发送
      },
      data: filterParams,
      success: (res) => {
        console.log('筛选接口响应：', res.data);
        if (res.data.code === 200) {
          const resultData = res.data.data;
          
          // 关键：使用本地存储传递数据
          wx.setStorageSync('counselorFilterResult', resultData);
          console.log('筛选结果已存储：', resultData);

          // 导航到目标页面
          wx.switchTab({
            url: '/pages/consult/consult',
            success: () => {
              console.log('导航成功');
            },
            fail: (err) => {
              console.error('导航失败：', err);
              wx.showToast({ 
                title: '导航失败，请稍后重试', 
                icon: 'none',
                duration: 3000
              });
            }
          });
        } else {
          wx.showToast({ title: '筛选失败: ' + (res.data.msg || '未知错误'), icon: 'none' });
        }
      },
      fail: (err) => {
        console.error('筛选请求失败', err);
        wx.showToast({ title: '网络请求失败', icon: 'none' });
      }
    });
  }
});